<template>
  <div style="width: 100%; height: 100%">
    <div class="toolbar-box">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
      />
    </div>
    <div class="editor-wrapper" v-if="editStyleRef.height">
      <div class="edit-title">
        <el-input v-model="form.name" placeholder="请输入文档标题" clearable />
      </div>
      <Editor
        :style="editStyleRef"
        v-model="valueHtmlRef"
        :defaultConfig="editorConfig"
        mode="default"
        @onCreated="handleCreated"
      />
      <div class="btns">
        <el-button
          type="info"
          class="cancel"
          round
          @click="() => router.back(-1)"
          >取消</el-button
        >
        <el-button type="primary" class="ok" round @click="handleClick"
          >确定</el-button
        >
      </div>
    </div>
  </div>
</template>
<script setup name="Edit">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import {
  onBeforeUnmount,
  ref,
  reactive,
  shallowRef,
  inject,
  onMounted,
  onUnmounted,
  nextTick,
  computed,
  watchEffect,
} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import useSymbols from './../../compostions/useSymbols.js';

import analysisDoc from '../../util/analysisDoc.js';
import { uploadFileApi } from '../../apis/uploadApi';
const imgBaseUrl = import.meta.env.VITE_BASE_FILE_SRC;

const router = useRouter();
const route = useRoute();

const { editMenoItemFun, getMenoDataItem } = inject(useSymbols);

const form = reactive({
  name: '',
});
const editStyleRef = ref({
  overflowY: 'hidden',
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtmlRef = ref('');
const toolbarConfig = {
  //去掉网络上传图片、视频、全屏
  excludeKeys: [
    'insertImage',
    'insertVideo',
    'uploadVideo',
    'group-video',
    'fullScreen',
  ],
};
const editorConfig = { placeholder: '请输入内容...', MENU_CONF: {} };

editorConfig.MENU_CONF['uploadImage'] = {
  // 自定义上传
  async customUpload(file, insertFn) {
    // JS 语法
    const base = await uploadFileApi(file);
    insertFn(imgBaseUrl + base, '', '');
  },
};
// 插入图片
editorConfig.MENU_CONF['insertImage'] = {
  onInsertedImage(imageNode) {
    // JS 语法
    if (imageNode == null) return;

    const { src, alt, url, href } = imageNode;
  },
};
// 编辑图片
editorConfig.MENU_CONF['editImage'] = {
  onUpdatedImage(imageNode) {
    // JS 语法
    if (imageNode == null) return;
    const { src, alt, url } = imageNode;
  },
};

// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor;
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

onMounted(() => {
  const debounceFun = debounce(getContentHeight, 50);
  debounceFun();
  window.addEventListener('resize', debounceFun);
  onUnmounted(() => {
    window.removeEventListener('resize', debounceFun);
  });
});

// 依赖route.query.id参数变化-加载数据
watchEffect(() => {
  if (route.query.id) {
    setTimeout(async () => {
      // getContentHeight();
      // 有id表示编辑状态
      await nextTick();
      const {
        name,
        content,
        createTime = null,
      } = await getMenoDataItem(route.query.id);
      // 富文本设置html
      editorRef.value.setHtml(content);
      // form赋值
      form.name = name;
      form.createTime = createTime;
    }, 100);
  } else {
    // 无id 新增
    setTimeout(() => {
      form.name = '';
      form.createTime = null;
      editorRef.value.setHtml('');
    }, 100);
  }
});

// 获取富文本内容高度
const getContentHeight = () => {
  const extraHeight = 188;
  const dom = document.querySelector('.toolbar-box');
  const toolberBoxHeight =
    dom.offsetHeight > 0 ? 0 : dom.offsetWidth > 1137 ? 40 : 80; //默认第一次加载无法获取高度，固定高度80
  const gapHeight = parseInt(
    dom.getBoundingClientRect().bottom + toolberBoxHeight + extraHeight
  );
  editStyleRef.value = {
    ...editStyleRef.value,
    height: `calc(100vh - ${gapHeight}px)`,
  };
};

// 保存
const handleClick = async () => {
  try {
    const content = valueHtmlRef.value;
    const { describe, src } = analysisDoc(content);
    const param = { content, ...form, describe, src: src || '' };
    if (route.query.id) {
      param.id = route.query.id;
    }
    await editMenoItemFun({ ...param });
    ElMessage({
      message: '便签保存成功！',
      type: 'success',
    });
    // router.back(-1);
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '保存失败！',
      type: 'error',
    });
  }
};
</script>
<style scoped>
.toolbar-box {
  width: calc(100% + 40px);
  margin-left: -20px;
  margin-top: -19px;
}
.editor-wrapper {
  --upload-width-height: 114px;
  border-radius: 15px;
  overflow: hidden;
  background-color: #ffffff;
  padding-bottom: 10px;
  margin-top: 16px;
  padding: 10px;
}

.form-wrapper {
  padding: 16px 16px 0px 16px;
}

.btns {
  text-align: right;
  padding: 15px 16px 10px 16px;
  box-sizing: border-box;
  border-top: 1px solid #dedede;
}

.cancel {
  color: #555;
  background-color: #eaeaea;
  border: none;
}

.ok {
  background-color: var(--system-primary-color);
  border: none;
}

.editor-wrapper >>> .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.editor-wrapper >>> .avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.editor-wrapper >>> .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: var(--upload-width-height);
  height: var(--upload-width-height);
  text-align: center;
  overflow: hidden;
}

.editor-wrapper >>> .avatar-uploader .avatar {
  width: var(--upload-width-height);
  height: var(--upload-width-height);
  display: block;
  overflow: hidden;
}

.edit-title {
  padding: 20px 0;
  border-bottom: 1px solid #e8e8e8;
}
.edit-title >>> .el-input__wrapper {
  box-shadow: none;
}
.edit-title >>> input {
  font-size: 26px;
  border: 0;
  outline: none;
  width: 100%;
  line-height: 1;
  color: #333;
}
</style>
